<template>
  <div class="song_related_video">
    <header class="header u-f u-f-ac">
      <div class="back_box u-f u-f-ac u-f-jc" @click="goBack">
        <i class="iconfont icon-jiantou"></i>
      </div>
      歌曲相关视频
    </header>
    <van-list
      v-model:loading="listState.loading"
      :finished="listState.finished"
      offset="100"
      finished-text="没有更多了"
      @load="loadMoreList"
    >
      <video-list
        class="min_height"
        v-for="item in tableData"
        :key="item.id"
        :data="item"
      >
      </video-list>
    </van-list>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, reactive, ref, Ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { timelineRecommend } from '@/api/video'
import VideoList from '@/components/common/video-list.vue'

// 暂停音乐播放
const handlePausesAuio = () => {
  const store = useStore()

  const audioObj = computed(() => store.state.audioObj)

  if (audioObj.value) {
    audioObj.value.pause()
    store.commit('setPlayOrPause', 'pause')
  }
}

// 处理列表
const handleList = () => {
  const tableData: Ref<Array<any>> = ref([])

  const listState = reactive({
    offset: 0, // 分页的页码
    loading: false,
    finished: false,
  })

  // 请求视频
  const getVideoList = async () => {
    const { data } = await timelineRecommend(listState.offset)
    if (listState.offset < 1) {
      tableData.value = []
    }

    for (const item of data.datas) {
      item.data.durationms = Math.floor(item.data.durationms / 1000)
      tableData.value.push(item.data)
    }
    setTimeout(() => {
      // 上拉结束，用定时器是防止页面还没渲染完，然后导致重复执行上拉加载事件
      listState.loading = false
    }, 1000)
    if (data.datas.length < 8 || !data.hasmore) {
      // 数据全部加载完成
      listState.finished = true
    }
  }

  // 上拉加载事件
  const loadMoreList = () => {
    getVideoList()
    listState.offset++
  }

  return {
    listState,
    tableData,
    loadMoreList,
    getVideoList,
  }
}

export default defineComponent({
  name: 'SongRelatedVideo',
  components: {
    VideoList,
  },
  setup() {
    const router = useRouter()

    const goBack = () => {
      router.go(-1)
    }

    handlePausesAuio()

    const { listState, tableData, loadMoreList, getVideoList } = handleList()

    return {
      listState,
      tableData,
      loadMoreList,
      getVideoList,
      goBack,
    }
  },
})
</script>

<style lang="less" scoped>
.song_related_video {
  min-height: 100vh;
  background-color: var(--sky-white-background-color);
  .header {
    position: sticky;
    left: 0;
    right: 0;
    top: 0;
    height: 50px;
    font-size: 20px;
    color: var(--sky-text-black-color);
    background-color: var(--sky-white-background-color);
    z-index: 2000;
    .back_box {
      width: 50px;
      height: 100%;
      .iconfont {
        font-size: 24px;
        color: var(--sky-text-black-color);
      }
    }
  }
  .min_height {
    min-height: 200px;
  }
}
</style>